import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import dotenv from "dotenv";
import fetch from 'node-fetch'
import sharp from "sharp";

dotenv.config();

// 获取iconfont的cookie和token
// 都可以在cookie或者在搜索一下，在请求头获取

// icon font 网站的cookie
const cookie = ``

// icon font 网站的token
const ctoken = ``

// Create server instance
// 创建一个服务端实例
const server = new McpServer({
  name: "iconfont-svg",
  version: "1.0.0",
  capabilities: {
    resources: {},
    tools: {},
  },
});


/**
 * @description 根据svg图标名称获取svg
 * @param svgName 获取的svgName
 * @param ids 已经获取过的id组合， 以 - 分隔
 * @returns 返回svg的信息
 */
async function getSvgIcon<T>(svgName: string, ids: string | undefined = undefined): Promise<T | null> {
  try {
    // 模拟请求，如果请求不行，请自行修改
    const headers = {
      accept: 'application/json, text/javascript, */*; q=0.01',
      'accept-encoding': 'gzip, deflate, br, zstd',
      'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
      'bx-v': '2.5.28',
      'cache-control': 'no-cache',
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
      cookie: cookie,
      origin: 'https://www.iconfont.cn',
      pragma: 'no-cache',
      referer: `https://www.iconfont.cn/search/index?searchType=icon&q=${svgName}&page=1&fromCollection=-1`,
      'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
      'sec-ch-ua-mobile': '?0',
      'sec-ch-ua-platform': '"Windows"',
      'sec-fetch-dest': 'empty',
      'sec-fetch-mode': 'cors',
      'sec-fetch-site': 'same-origin',
      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
      'x-csrf-token': ctoken,
      'x-requested-with': 'XMLHttpRequest'
    };

    // 表单数据
    const formData = new URLSearchParams({
      q: `${svgName}`,
      sortType: 'updated_at',
      page: '1',
      pageSize: '54',
      sType: '',
      fromCollection: '-1',
      fills: '',
      t: `${(new Date()).getTime()}`,
      ctoken: ctoken
    }).toString();

    // 发送请求
    const response = await fetch('https://www.iconfont.cn/api/icon/search.json', {
      method: 'POST',
      headers: headers,
      body: formData
    });
    // 获取json
    const resJSON = await response.json() as any;
    if (resJSON?.code === 200) {
      // 如果ids不存在，就是纯粹获取
      if (!ids) {
        return resJSON?.data.icons?.[0];
      }
      // 当ids存在，就是换一个图标
      else {
        // 分割ids获取id数组
        const _ids = ids.split('-').map(id => {
          return parseInt(id)
        })
        // 返回第一个id不包含在_ids中的icon
        return resJSON?.data?.icons?.filter((icon: any) => {
          return !_ids.includes(icon.id)
        })?.[0]
      }
    }
    else {
      throw new Error(`Failed to fetch svg data: ${response.statusText}`);
    }
  } catch (error) {
    console.error(error);
    return null;
  }
}

// 根据名称获取svg图标的tool
server.tool(
  'get-svg',
  '根据svg图标名称获取svg',
  {
    svgName: z.string().describe('svg图标名称'),
  },
  async ({ svgName }) => {
    const svg = await getSvgIcon<{
      id: number;
      name: string;
      status: number;
      is_private: number;
      category_id: string;
      slug: string;
      unicode: string;
      width: number;
      height: number;
      defs: null | string; // 假设defs可以为null或字符串
      path_attributes: string;
      fills: number;
      font_class: string;
      user_id: number;
      repositorie_id: number;
      created_at: string;
      updated_at: string;
      svg_hash: string;
      svg_fill_hash: string;
      fork_from: null | number; // 假设fork_from可以为null或数字
      deleted_at: null | string; // 假设deleted_at可以为null或字符串
      show_svg: string;
    }>(svgName);

    if (!svg) {
      return {
        content: [{
          type: 'text',
          text: '获取svg失败，请检查svg名称是否正确'
        }]
      }
    }

    const formattedSvg = `
    svg图标名称: ${svg.name},
    show_svg: ${svg.show_svg},
    path_attributes: ${svg.path_attributes},
    id: ${svg.id},
    ids:  ${svg.id}
    `;
   /*  
    // 目前cursor不支持type: image的消息， 后续支持可以传预览图
    const buffer = await sharp(Buffer.from(svg.show_svg)).resize(128, 128) // 设置宽度和高度为128px
    .png().toBuffer();
    const base64 = buffer.toString('base64') */
    return {
      content: [{
        type: 'text',
        text: formattedSvg
      },
      /* {
        "type": "image",
        "data": base64,
        "mimeType": "image/png"
      } */
    ]
    }
  }
)

// 根据ids和svg图标名称去重新获取一个新的svg
server.tool('change-svg', '根据id和svg图标名称去重新获取一个新的svg', {
  svgName: z.string().describe('svg图标名称'),
  id: z.string().describe('之前获取的相同名称的svg图标的id'),
  ids: z.string().describe('之前获取的相同名称的svg图标的ids')
}, async ({ svgName, id, ids }) => {
  const svg = await getSvgIcon(svgName, ids) as any;
  if (!svg) {
    return {
      content: [{
        type: 'text',
        text: '获取svg失败，请检查svg名称是否正确'
      }]
    };
  }
  const formattedSvg = `
  svg图标名称: ${svg.name},
  show_svg: ${svg.show_svg},
  path_attributes: ${svg.path_attributes},
  id: ${svg.id},
  ids: ${ids}-${svg.id}
  `;
  return {
    content: [{
      type: 'text',
      text: formattedSvg
    }]
  };
})

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("SVG MCP Server running on stdio");
}

// 启动
main().catch((error) => {
  console.error("Fatal error in main():", error);
  process.exit(1);
});